﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using M139.Api;

public partial class _Default : System.Web.UI.Page
{
    M139ApiService m139 = new M139ApiService();
    string _url;
    protected void Page_Load(object sender, EventArgs e)
    {
        _url = "http://localhost:1111/";
        post.Visible = false;
        login.Visible = false;
        if (Request["oauth_verifier"] != null)
        {
            post.Visible = false;
            if (Request["target"] == "139")
            {
                m139.Token = Session["oauth_token_139"].ToString();
                m139.TokenSecret = Session["oauth_token_secret_139"].ToString();
                m139.oAuthWeb(Request["oauth_token"].ToString(), Request["oauth_verifier"].ToString());
                Session["oauth_token_139"] = m139.Token;
                Session["oauth_token_secret_139"] = m139.TokenSecret;
                Response.Redirect(_url);
            }

        }

        if (Session["oauth_token_139"] != null)
        {
            Btn139.Visible = false;
            post.Visible = true;
            login.Visible = true;
            m139.Token = Session["oauth_token_139"].ToString();
            m139.TokenSecret = Session["oauth_token_secret_139"].ToString();

            M139.Api.User u = m139.user_getinfo();
            if (u != null)
            {
                lblUser.Text ="欢迎你，"+ (string.IsNullOrEmpty(u.nickname) ? u.screen_name : u.nickname);
                imgAvator.ImageUrl = u.icon80;
            }

        }
    }

    protected void Btn139_Click(object sender, EventArgs e)
    {
        M139ApiService api = new M139ApiService();
        string url = api.AuthorizationGet();

        //保存Token和TokenSecret供下一步调用接口用
        Session["oauth_token_139"] = api.Token;
        Session["oauth_token_secret_139"] = api.TokenSecret;
        Response.Redirect(url + "&oauth_callback=" + Server.UrlEncode(_url + "?target=139"));
    }


    protected void BtnPost_Click(object sender, EventArgs e)
    {
        m139.Token = Session["oauth_token_139"].ToString();
        m139.TokenSecret = Session["oauth_token_secret_139"].ToString();
        lblSent.Text = "已成功发布以下内容到说客：<br/><br/>" + m139.posttext(content.Text.Trim()).text;
    }

    protected void BtnLogout_Click(object sender, EventArgs e)
    {
        Session["oauth_token_139"] = null;
        Session["oauth_token_secret_139"] = null;
        Response.Redirect(_url);
    }
}